package com.bit.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketServer {

    private static EventLoopGroup worker = new NioEventLoopGroup();
    private static EventLoopGroup boss = new NioEventLoopGroup();

    public void bind(String ip, int port) {
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(worker, boss)
            .channel(NioServerSocketChannel.class)
//                    .option(ChannelOption.)
            .handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel sc) throws Exception {
                    //将请求解码为HTTP消息
                    sc.pipeline().addLast("http-codec",new HttpServerCodec());
                    //将http多个组成部分组成一个完整的HTTP消息
                    sc.pipeline().addLast("aggreator", new HttpObjectAggregator(65535));
                    // 向客户端发送 html5文件，支持服务端通信
                    sc.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                    sc.pipeline().addLast("handler", new WebSocketServerHandler());
                }
            });
            Channel channel = sb.bind(ip, port).sync().channel();
            channel.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }

}
